<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 设置警告提示 -->
      <el-alert
        show-icon
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
      >
      </el-alert>
      <!-- 级联选择器 -->
      <span>选择商品分类 : </span>
      <el-cascader
        v-model="optCateDate"
        :options="goodsCateDate"
        :props="cascProps"
        @change="optHandleChange">
    </el-cascader>
    <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many" tab-click="conditionClick">
          <el-button type="primary" size="small" :disabled="conditionAndStatic" @click="openAddManyAndOnly">添加参数</el-button>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only" tab-click="smallClick">
          <el-button type="primary" size="small" :disabled="conditionAndStatic" @click="openAddManyAndOnly">添加属性</el-button>
        </el-tab-pane>
      </el-tabs>
      <!-- table表格 -->
      <el-table
        :data="paramsData"
        border
        style="width: 100%">
        <el-table-column type="expand" label="">
          <template slot-scope="scope">
            <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="delTag(scope.row, index)">{{item}}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="scope.row.inputVisible"
              v-model="scope.row.tInputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm(scope.row)"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column
          prop="attr_name"
          label="参数名称"
        >
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini" @click="upDialog(scope.row)">修改</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="delClassify(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="closeAddDialog"
    >
      <el-form ref="addFormRef" :model="manyAndonlyFormData" :rules="addFormRules" label-width="80px">
        <el-form-item :label="label" prop="InVal">
          <el-input v-model="manyAndonlyFormData.InVal"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addManyAndOnly()">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="upDialogVisible"
      width="50%"
    >
      <el-form ref="upFormRef" :model="upManyAndonlyFormData" :rules="upFormRules" label-width="80px">
        <el-form-item :label="label" prop="attr_name">
          <el-input v-model="upManyAndonlyFormData.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="upDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="upDialogVisibleClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // casc 双向绑定的数据
      optCateDate: [],
      // casc 所有数据
      goodsCateDate: [],
      // casc 配置项
      cascProps: {
        expandTrigger: 'hover',
        // 渲染casc(goodsCateDate)数据中指定字段
        label: 'cat_name',
        // 往v-model里传入指定的字段
        value: 'cat_id'
      },
      // 设置tabs标签页默认选项
      activeName: 'many',
      // 静态属性 和动态参数的Flag
      conditionAndStatic: true,
      // 静态属性和动态参数的数据
      paramsData: [],
      // 添加参数对话框
      addDialogVisible: false,
      manyAndonlyFormData: {
        InVal: ''
      },
      // 添加对话框Label
      label: '动态参数',
      // 添加参数对话框验证规则
      addFormRules: {
        InVal: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 修改参数验证规则
      upFormRules: {
        attr_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
          { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
        ]
      },
      // 修改表单对话框flag
      upDialogVisible: false,
      // 修改表单对话栏数据
      upManyAndonlyFormData: {}
    }
  },
  created () {
    this.getGoodsList()
  },
  methods: {
    // 获取分类数据列表
    async getGoodsList () {
      const { data: res } = await this.$axios.get('categories')
      this.goodsCateDate = res.data
    },
    // 级联选择器选中某项时触发事件
    optHandleChange () {
      if (this.optCateDate.length !== 3) {
        this.optCateDate = []
        this.paramsData = []
        this.conditionAndStatic = true
        return
      }
      this.getParams()
    },
    // 获取动态或静态参数
    async getParams () {
      const threeId = this.optCateDate[this.optCateDate.length - 1]
      if (this.activeName === 'many') {
        const { data: res } = await this.$axios.get(`categories/${threeId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        // 循环返回数据 且给每行input添加单独的flag
        // 注意这里先添加再付值
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          item.inputVisible = false
          item.tInputValue = ''
        })
        this.paramsData = res.data
        this.conditionAndStatic = false
      } else {
        const { data: res } = await this.$axios.get(`categories/${threeId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
          item.inputVisible = false
          item.tInputValue = ''
        })
        this.paramsData = res.data
        this.conditionAndStatic = false
      }
    },
    handleClick () {
      this.getParams()
    },
    // tag输入框事件
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 添加tag
    async handleInputConfirm (row) {
      if (!row.tInputValue) {
        row.inputVisible = false
        return
      }
      const tInputValue = row.tInputValue
      row.attr_vals.push(tInputValue)
      this.editTag(row)
    },
    // 删除tag
    delTag (row, index) {
      row.attr_vals.splice(index, 1)
      this.editTag(row, index)
    },
    // 编辑tag
    async editTag (row, index) {
      const { data: res } = await this.$axios.put(`categories/${row.cat_id}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(',')
      })
      console.log(res.data)
      if (res.meta.status !== 200) return this.$message(res.meta.status)
      if (index) {
        this.$message('删除成功')
      } else {
        this.$message.success('修改成功')
      }
      row.inputVisible = false
      row.tInputValue = ''
    },
    // 打开添加参数对话框
    openAddManyAndOnly () {
      this.activeName === 'many' ? this.label = '动态参数' : this.label = '静态数据'
      this.addDialogVisible = true
    },
    // 定义添加分类方法
    async addManyAndOnlys (row) {
      console.log(row)
      const { data: res } = await this.$axios.post(`categories/${row[2]}/attributes`, {
        attr_name: this.manyAndonlyFormData.InVal,
        attr_sel: this.activeName
      })
      if (res.meta.status !== 201) return this.$message.error('编辑失败')
      this.getParams()
      this.addDialogVisible = false
      this.$message.success('编辑成功')
    },
    // 添加分类窗口关闭后 重置表单
    closeAddDialog () {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定 验证添加属性对话框 且发起请求
    addManyAndOnly () {
      console.log(this.$refs)
      this.$refs.addFormRef.validate(flag => {
        if (!flag) return
        this.addManyAndOnlys(this.optCateDate)
      })
    },
    async upDialog (row) {
      this.activeName === 'many' ? this.label = '动态参数' : this.label = '静态数据'
      this.upDialogVisible = true
      const { data: res } = await this.$axios.get(`categories/${this.optCateDate[2]}/attributes/${row.attr_id}`)
      this.upManyAndonlyFormData = res.data
    },
    upDialogVisibleClick () {
      this.$refs.upFormRef.validate(async flag => {
        if (!flag) return
        const { data: res } = await this.$axios.put(`categories/${this.optCateDate[2]}/attributes/${this.upManyAndonlyFormData.attr_id}`, {
          attr_name: this.upManyAndonlyFormData.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('更新失败')
        this.$message.success(res.meta.msg)
        this.getParams()
        this.upDialogVisible = false
      })
    },
    // 删除分类
    delClassify (row) {
      this.$messageBox.confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`categories/${this.optCateDate[2]}/attributes/${row.attr_id}`)
        if (res.meta.status !== 200) return this.$message.error('删除失败')
        this.$message.success('删除成功!')
        this.getParams()
      }).catch(() => {
        this.$message('已取消删除')
      })
    }
  }
}
</script>

<style scoped>
.el-alert{
  margin: 10px 0 30px 0;
}
.el-tag{
  margin: 5px;
}
.input-new-tag{
  width: 90px;
}
</style>
